// icon-settings.js - TabBar图标设置页面
const app = getApp()

Page({
  data: {
    hasPermission: false,
    currentTab: 'home',
    showUploadModal: false,
    currentIconType: '',
    uploadState: 'normal', // normal | selected
    tempImageUrl: '',
    uploading: false,
    uploadProgress: 0,
    uploadStatus: '准备上传...',
    
    // TabBar项目配置
    tabbarItems: [
      { type: 'home', text: '小家', icon: '/images/tabbar/home.png' },
      { type: 'dishes', text: '味道', icon: '/images/tabbar/dishes.png' },
      { type: 'cart', text: '喜欢', icon: '/images/tabbar/cart.png' },
      { type: 'orders', text: '日记', icon: '/images/tabbar/orders.png' },
      { type: 'profile', text: '自己', icon: '/images/tabbar/profile.png' }
    ],
    
    // 图标配置
    iconConfigs: [
      {
        type: 'home',
        name: '小家',
        description: '首页导航图标',
        currentIcon: '/images/tabbar/home.png',
        normalIcon: '/images/tabbar/home.png',
        selectedIcon: '/images/tabbar/home-active.png',
        hasCustom: false
      },
      {
        type: 'dishes',
        name: '味道',
        description: '菜品页面图标',
        currentIcon: '/images/tabbar/dishes.png',
        normalIcon: '/images/tabbar/dishes.png',
        selectedIcon: '/images/tabbar/dishes-active.png',
        hasCustom: false
      },
      {
        type: 'cart',
        name: '喜欢',
        description: '收藏页面图标',
        currentIcon: '/images/tabbar/cart.png',
        normalIcon: '/images/tabbar/cart.png',
        selectedIcon: '/images/tabbar/cart-active.png',
        hasCustom: false
      },
      {
        type: 'orders',
        name: '日记',
        description: '订单记录图标',
        currentIcon: '/images/tabbar/orders.png',
        normalIcon: '/images/tabbar/orders.png',
        selectedIcon: '/images/tabbar/orders-active.png',
        hasCustom: false
      },
      {
        type: 'profile',
        name: '自己',
        description: '个人中心图标',
        currentIcon: '/images/tabbar/profile.png',
        normalIcon: '/images/tabbar/profile.png',
        selectedIcon: '/images/tabbar/profile-active.png',
        hasCustom: false
      }
    ]
  },

  onLoad() {
    this.checkCloudEnvironment()
    this.checkUserPermission()
    this.loadTabBarIcons()
  },

  onShow() {
    this.loadTabBarIcons()
  },

  // 检查云开发环境
  checkCloudEnvironment() {
    if (!wx.cloud) {
      wx.showModal({
        title: '环境错误',
        content: '当前环境不支持云开发功能',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }
    
    try {
      wx.cloud.init({
        env: 'cloudbase-9ghiew2sb390831b'
      })
      console.log('云开发环境已初始化')
    } catch (error) {
      console.error('云开发环境初始化失败:', error)
    }
  },

  // 检查用户权限
  checkUserPermission() {
    const userInfo = app.globalData.userInfo
    const userRole = app.globalData.userRole
    
    console.log('检查权限 - userInfo:', userInfo, 'userRole:', userRole)
    
    // 检查权限：chef（厨师）和admin（管理员）都可以设置图标
    const hasPermission = (userInfo && (userInfo.role === 'chef' || userInfo.role === 'admin')) ||
                         (userRole === 'chef' || userRole === 'admin')
    
    this.setData({ hasPermission })
    
    if (!hasPermission) {
      console.log('用户权限不足，无法设置TabBar图标')
    }
  },

  // 加载TabBar图标配置
  async loadTabBarIcons() {
    if (!this.data.hasPermission) return
    
    try {
      console.log('开始加载TabBar图标配置...')
      
      const result = await wx.cloud.callFunction({
        name: 'getTabBarIcons'
      })
      
      console.log('云函数返回结果:', result)
      
      if (result.result && result.result.success && result.result.data) {
        this.updateIconConfigs(result.result.data)
        this.updateTabBarPreview(result.result.data)
        console.log('TabBar图标配置加载成功')
      } else {
        console.log('暂无自定义TabBar图标配置，使用默认配置')
        // 即使无配置，也要调用更新方法来显示默认状态
        this.updateIconConfigs({})
        this.updateTabBarPreview({})
      }
      
    } catch (error) {
      console.error('加载TabBar图标配置失败:', error)
      
      if (error.errCode === -501000) {
        console.log('云函数未部署，使用默认配置')
        wx.showToast({
          title: '需要先部署云函数',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '加载配置失败',
          icon: 'error'
        })
      }
    }
  },

  // 更新图标配置数据
  updateIconConfigs(cloudIcons) {
    const iconConfigs = this.data.iconConfigs.map(config => {
      const cloudIcon = cloudIcons[config.type]
      if (cloudIcon) {
        return {
          ...config,
          currentIcon: cloudIcon.normal,
          normalIcon: cloudIcon.normal,
          selectedIcon: cloudIcon.selected,
          hasCustom: true
        }
      } else {
        // 当云端无配置时，恢复默认图标显示
        const defaultIcons = {
          home: { normal: '/images/tabbar/home.png', selected: '/images/tabbar/home-active.png' },
          dishes: { normal: '/images/tabbar/dishes.png', selected: '/images/tabbar/dishes-active.png' },
          cart: { normal: '/images/tabbar/cart.png', selected: '/images/tabbar/cart-active.png' },
          orders: { normal: '/images/tabbar/orders.png', selected: '/images/tabbar/orders-active.png' },
          profile: { normal: '/images/tabbar/profile.png', selected: '/images/tabbar/profile-active.png' }
        }
        const defaultIcon = defaultIcons[config.type]
        return {
          ...config,
          currentIcon: defaultIcon.normal,
          normalIcon: defaultIcon.normal,
          selectedIcon: defaultIcon.selected,
          hasCustom: false
        }
      }
    })
    
    this.setData({ iconConfigs })
    console.log('图标配置已更新:', iconConfigs)
  },

  // 更新TabBar预览
  updateTabBarPreview(cloudIcons) {
    const tabbarItems = this.data.tabbarItems.map(item => {
      const cloudIcon = cloudIcons[item.type]
      if (cloudIcon) {
        // 优先使用云存储图标，确保 URL格式正确
        let normalIcon = item.icon // 默认图标
        let selectedIcon = item.icon // 默认图标
        
        // 处理普通状态图标
        if (cloudIcon.normal) {
          normalIcon = cloudIcon.normal
          console.log(`${item.type} 普通状态图标更新为:`, normalIcon)
        }
        
        // 处理选中状态图标
        if (cloudIcon.selected) {
          selectedIcon = cloudIcon.selected
          console.log(`${item.type} 选中状态图标更新为:`, selectedIcon)
        } else if (cloudIcon.normal) {
          // 如果没有选中状态图标，使用普通状态图标
          selectedIcon = cloudIcon.normal
        }
        
        return {
          ...item,
          icon: this.data.currentTab === item.type ? selectedIcon : normalIcon
        }
      } else {
        // 当云端无配置时，恢复默认图标
        const defaultIcons = {
          home: { normal: '/images/tabbar/home.png', selected: '/images/tabbar/home-active.png' },
          dishes: { normal: '/images/tabbar/dishes.png', selected: '/images/tabbar/dishes-active.png' },
          cart: { normal: '/images/tabbar/cart.png', selected: '/images/tabbar/cart-active.png' },
          orders: { normal: '/images/tabbar/orders.png', selected: '/images/tabbar/orders-active.png' },
          profile: { normal: '/images/tabbar/profile.png', selected: '/images/tabbar/profile-active.png' }
        }
        const defaultIcon = defaultIcons[item.type]
        return {
          ...item,
          icon: this.data.currentTab === item.type ? defaultIcon.selected : defaultIcon.normal
        }
      }
    })
    
    this.setData({ tabbarItems })
    console.log('TabBar预览更新完成，新数据:', tabbarItems)
  },

  // 切换预览标签
  switchPreviewTab(e) {
    const type = e.currentTarget.dataset.type
    this.setData({ currentTab: type })
    
    // 更新预览图标显示
    const tabbarItems = this.data.tabbarItems.map(item => ({
      ...item,
      icon: type === item.type ? 
        this.getIconPath(item.type, 'selected') : 
        this.getIconPath(item.type, 'normal')
    }))
    
    this.setData({ tabbarItems })
  },

  // 获取图标路径
  getIconPath(type, state) {
    const config = this.data.iconConfigs.find(c => c.type === type)
    if (!config) return '/images/tabbar/home.png'
    
    const iconPath = state === 'selected' ? config.selectedIcon : config.normalIcon
    
    // 确保返回有效的路径
    if (!iconPath) {
      // 如果没有路径，返回默认图标
      const defaultIcons = {
        home: state === 'selected' ? '/images/tabbar/home-active.png' : '/images/tabbar/home.png',
        dishes: state === 'selected' ? '/images/tabbar/dishes-active.png' : '/images/tabbar/dishes.png',
        cart: state === 'selected' ? '/images/tabbar/cart-active.png' : '/images/tabbar/cart.png',
        orders: state === 'selected' ? '/images/tabbar/orders-active.png' : '/images/tabbar/orders.png',
        profile: state === 'selected' ? '/images/tabbar/profile-active.png' : '/images/tabbar/profile.png'
      }
      return defaultIcons[type] || '/images/tabbar/home.png'
    }
    
    // 对于云存储URL，直接返回（微信会自动处理）
    if (iconPath.startsWith('cloud://')) {
      return iconPath
    }
    
    // 对于其他格式的URL，直接返回
    return iconPath
  },

  // 上传图标
  uploadIcon(e) {
    const type = e.currentTarget.dataset.type
    const config = this.data.iconConfigs.find(c => c.type === type)
    
    this.setData({
      showUploadModal: true,
      currentIconType: config.name,
      uploadState: 'normal',
      tempImageUrl: '',
      uploading: false,
      uploadProgress: 0
    })
  },

  // 重置图标
  resetIcon(e) {
    const type = e.currentTarget.dataset.type
    const config = this.data.iconConfigs.find(c => c.type === type)
    
    wx.showModal({
      title: '确认重置',
      content: `确定要将${config.name}图标恢复为默认样式吗？`,
      success: async (res) => {
        if (res.confirm) {
          await this.clearIconConfig(type)
        }
      }
    })
  },

  // 清除图标配置
  async clearIconConfig(iconType) {
    try {
      wx.showLoading({ title: '正在重置...' })
      
      const result = await wx.cloud.callFunction({
        name: 'setTabBarIcon',
        data: {
          iconType: iconType,
          action: 'clear'
        }
      })
      
      console.log('清除图标配置结果:', result)
      
      if (result.result && result.result.success) {
        wx.showToast({
          title: '重置成功',
          icon: 'success'
        })
        
        // 清除等待中的TabBar配置（避免意外应用之前的配置）
        if (app.globalData) {
          app.globalData.pendingTabBarIcons = null
        }
        wx.removeStorageSync('pendingTabBarIcons')
        
        // 重新加载配置
        await this.loadTabBarIcons()
        
        // 通知app更新TabBar
        if (app.refreshTabBarIcons) {
          await app.refreshTabBarIcons()
        }
      } else {
        throw new Error(result.result.message || '重置失败')
      }
      
    } catch (error) {
      console.error('重置图标失败:', error)
      wx.showToast({
        title: '重置失败',
        icon: 'error'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 隐藏上传模态框
  hideUploadModal() {
    this.setData({
      showUploadModal: false,
      tempImageUrl: '',
      uploading: false
    })
  },

  // 阻止事件冒泡
  preventClose() {
    // 空函数，用于阻止模态框内容区域的点击事件冒泡
  },

  // 切换上传状态
  switchUploadState(e) {
    const state = e.currentTarget.dataset.state
    this.setData({ 
      uploadState: state,
      tempImageUrl: '' // 切换状态时清空临时图片
    })
  },

  // 选择图片
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        console.log('选择的图片路径:', tempFilePath)
        
        this.setData({
          tempImageUrl: tempFilePath
        })
      },
      fail: (error) => {
        console.error('选择图片失败:', error)
        wx.showToast({
          title: '选择图片失败',
          icon: 'error'
        })
      }
    })
  },

  // 拍摄照片
  takePhoto() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        console.log('拍摄的图片路径:', tempFilePath)
        
        this.setData({
          tempImageUrl: tempFilePath
        })
      },
      fail: (error) => {
        console.error('拍摄照片失败:', error)
        wx.showToast({
          title: '拍摄照片失败',
          icon: 'error'
        })
      }
    })
  },

  // 确认上传
  async confirmUpload() {
    if (!this.data.tempImageUrl) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'none'
      })
      return
    }
    
    this.setData({ 
      uploading: true,
      uploadProgress: 0,
      uploadStatus: '正在上传图片...'
    })
    
    try {
      // 1. 上传图片到云存储
      const cloudPath = `tabbar_icons/${this.getCurrentIconType()}_${this.data.uploadState}_${Date.now()}.png`
      
      this.setData({ uploadStatus: '正在上传到云存储...' })
      
      console.log('开始上传图片到云存储...', {
        cloudPath: cloudPath,
        filePath: this.data.tempImageUrl
      })
      
      const uploadResult = await wx.cloud.uploadFile({
        cloudPath: cloudPath,
        filePath: this.data.tempImageUrl
      })
      
      console.log('上传成功，fileID:', uploadResult.fileID)
      
      if (!uploadResult.fileID) {
        throw new Error('图片上传失败，未获取到fileID')
      }
      
      this.setData({ uploadProgress: 50 })
      
      this.setData({ 
        uploadProgress: 70,
        uploadStatus: '正在保存配置...'
      })
      
      // 2. 获取当前配置，准备更新
      const currentConfig = this.data.iconConfigs.find(c => c.type === this.getCurrentIconType())
      
      // 确定最终的图标URL
      let normalIcon, selectedIcon
      
      if (this.data.uploadState === 'normal') {
        // 上传普通状态图标
        normalIcon = uploadResult.fileID
        // 如果选中状态是云存储URL，保持不变；否则使用新上传的图标
        selectedIcon = (currentConfig.selectedIcon && currentConfig.selectedIcon.startsWith('cloud://')) 
                      ? currentConfig.selectedIcon 
                      : uploadResult.fileID
      } else {
        // 上传选中状态图标
        selectedIcon = uploadResult.fileID
        // 如果普通状态是云存储URL，保持不变；否则使用新上传的图标
        normalIcon = (currentConfig.normalIcon && currentConfig.normalIcon.startsWith('cloud://')) 
                    ? currentConfig.normalIcon 
                    : uploadResult.fileID
      }
      
      console.log('最终图标配置:', { normalIcon, selectedIcon })
      
      // 3. 调用云函数保存配置
      const setResult = await wx.cloud.callFunction({
        name: 'setTabBarIcon',
        data: {
          iconType: this.getCurrentIconType(),
          imageUrl: normalIcon,
          selectedImageUrl: selectedIcon
        }
      })
      
      console.log('设置图标配置结果:', setResult)
      
      if (setResult.result && setResult.result.success) {
        this.setData({ 
          uploadProgress: 100,
          uploadStatus: '上传成功！'
        })
        
        wx.showToast({
          title: '设置成功，请切换到首页查看效果',
          icon: 'success',
          duration: 2000
        })
        
        // 重新加载配置
        await this.loadTabBarIcons()
        
        // 通知app更新TabBar
        if (app.refreshTabBarIcons) {
          app.refreshTabBarIcons()
        }
        
        // 延迟关闭模态框
        setTimeout(() => {
          this.hideUploadModal()
        }, 1000)
        
      } else {
        throw new Error(setResult.result.message || '设置失败')
      }
      
    } catch (error) {
      console.error('上传图标失败:', error)
      wx.showToast({
        title: '上传失败',
        icon: 'error'
      })
      
      this.setData({
        uploading: false,
        uploadProgress: 0,
        uploadStatus: '上传失败'
      })
    }
  },

  // 获取当前图标类型
  getCurrentIconType() {
    const typeMap = {
      '小家': 'home',
      '味道': 'dishes', 
      '喜欢': 'cart',
      '日记': 'orders',
      '自己': 'profile'
    }
    
    return typeMap[this.data.currentIconType] || 'home'
  }
})